package com.hxzy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hxzy.common.enums.AckCode;
import com.hxzy.common.exception.ServiceException;
import com.hxzy.common.util.WaimaiThreadLocal;
import com.hxzy.common.vo.resp.R;
import com.hxzy.controller.mobile.addressbook.req.AddressBookAddReq;
import com.hxzy.controller.mobile.login.resp.MobileLoginResp;
import com.hxzy.controller.mobile.mapstruct.AddressBookConvert;
import com.hxzy.entity.AddressBook;
import com.hxzy.service.AddressBookService;
import com.hxzy.mapper.AddressBookMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
* @author Administrator
* @description 针对表【address_book(地址管理)】的数据库操作Service实现
* @createDate 2023-06-28 16:38:44
*/
@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook>
    implements AddressBookService{


    @Override
    public boolean add(AddressBookAddReq req) {
        //谁买的
        Integer userId= WaimaiThreadLocal.mobileLoginThreadLocal.get().getId();

        //查询该用户是否有默认的收货地址
        LambdaQueryWrapper<AddressBook> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(AddressBook::getUserId,userId);
        queryWrapper.eq(AddressBook::getIsDeleted,"0");
        queryWrapper.eq(AddressBook::getIsDefault,"0");
        long count = super.count(queryWrapper);

        //转换自己的对象
        AddressBook entity = AddressBookConvert.INSTANCE.convert(req);
        entity.setUserId(new Long(userId));
        entity.setIsDeleted("0");

        //是否是默认值
        entity.setIsDefault( count==0?"0": "1");

        return super.save(entity);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateDefaultAddress(Long id) {
        AddressBook db = this.getById(id);
        if(Objects.isNull(db)){
            throw new ServiceException(AckCode.NOT_FOUND_DATA);
        }

        //默认本身就是收货地址
        if(db.getIsDefault().equals("0")){
            throw new ServiceException(AckCode.ADDRESS_SET_DEFAULT);
        }

        //执行2条sql，1、把当前用户所有的默认收货地址设为不默认1
        MobileLoginResp mobileLoginResp = WaimaiThreadLocal.mobileLoginThreadLocal.get();
        this.getBaseMapper().cancelDefaultAddress(mobileLoginResp.getId(),mobileLoginResp.getUserName());

        //2、更改当前数据，把收货地址更改为 0
        db.setIsDefault("0");
        super.updateById(db);

        return true;
    }
}




